/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ru.ibrae.mchs.radiation.entities.controllers;

import ru.ibrae.mchs.radiation.entities.DicUnit;
import ru.ibrae.mchs.radiation.entities.controllers.exceptions.NonexistentEntityException;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import ru.ibrae.mchs.radiation.entities.Result;
import java.util.HashSet;
import java.util.Set;

/**
 *
 * @author murr
 */
public class DicUnitJpaController {

    public DicUnitJpaController() {
        emf = Persistence.createEntityManagerFactory("DesktopApplication4PU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(DicUnit dicUnit) {
        if (dicUnit.getResultSet() == null) {
            dicUnit.setResultSet(new HashSet<Result>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Set<Result> attachedResultSet = new HashSet<Result>();
            for (Result resultSetResultToAttach : dicUnit.getResultSet()) {
                resultSetResultToAttach = em.getReference(resultSetResultToAttach.getClass(), resultSetResultToAttach.getIdRezult());
                attachedResultSet.add(resultSetResultToAttach);
            }
            dicUnit.setResultSet(attachedResultSet);
            em.persist(dicUnit);
            for (Result resultSetResult : dicUnit.getResultSet()) {
                DicUnit oldDicUnitOfResultSetResult = resultSetResult.getDicUnit();
                resultSetResult.setDicUnit(dicUnit);
                resultSetResult = em.merge(resultSetResult);
                if (oldDicUnitOfResultSetResult != null) {
                    oldDicUnitOfResultSetResult.getResultSet().remove(resultSetResult);
                    oldDicUnitOfResultSetResult = em.merge(oldDicUnitOfResultSetResult);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(DicUnit dicUnit) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            DicUnit persistentDicUnit = em.find(DicUnit.class, dicUnit.getIdUnit());
            Set<Result> resultSetOld = persistentDicUnit.getResultSet();
            Set<Result> resultSetNew = dicUnit.getResultSet();
            Set<Result> attachedResultSetNew = new HashSet<Result>();
            for (Result resultSetNewResultToAttach : resultSetNew) {
                resultSetNewResultToAttach = em.getReference(resultSetNewResultToAttach.getClass(), resultSetNewResultToAttach.getIdRezult());
                attachedResultSetNew.add(resultSetNewResultToAttach);
            }
            resultSetNew = attachedResultSetNew;
            dicUnit.setResultSet(resultSetNew);
            dicUnit = em.merge(dicUnit);
            for (Result resultSetOldResult : resultSetOld) {
                if (!resultSetNew.contains(resultSetOldResult)) {
                    resultSetOldResult.setDicUnit(null);
                    resultSetOldResult = em.merge(resultSetOldResult);
                }
            }
            for (Result resultSetNewResult : resultSetNew) {
                if (!resultSetOld.contains(resultSetNewResult)) {
                    DicUnit oldDicUnitOfResultSetNewResult = resultSetNewResult.getDicUnit();
                    resultSetNewResult.setDicUnit(dicUnit);
                    resultSetNewResult = em.merge(resultSetNewResult);
                    if (oldDicUnitOfResultSetNewResult != null && !oldDicUnitOfResultSetNewResult.equals(dicUnit)) {
                        oldDicUnitOfResultSetNewResult.getResultSet().remove(resultSetNewResult);
                        oldDicUnitOfResultSetNewResult = em.merge(oldDicUnitOfResultSetNewResult);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = dicUnit.getIdUnit();
                if (findDicUnit(id) == null) {
                    throw new NonexistentEntityException("The dicUnit with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            DicUnit dicUnit;
            try {
                dicUnit = em.getReference(DicUnit.class, id);
                dicUnit.getIdUnit();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The dicUnit with id " + id + " no longer exists.", enfe);
            }
            Set<Result> resultSet = dicUnit.getResultSet();
            for (Result resultSetResult : resultSet) {
                resultSetResult.setDicUnit(null);
                resultSetResult = em.merge(resultSetResult);
            }
            em.remove(dicUnit);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<DicUnit> findDicUnitEntities() {
        return findDicUnitEntities(true, -1, -1);
    }

    public List<DicUnit> findDicUnitEntities(int maxResults, int firstResult) {
        return findDicUnitEntities(false, maxResults, firstResult);
    }

    private List<DicUnit> findDicUnitEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(DicUnit.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public DicUnit findDicUnit(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(DicUnit.class, id);
        } finally {
            em.close();
        }
    }

    public int getDicUnitCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<DicUnit> rt = cq.from(DicUnit.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
